<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Menu;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class MenuController extends Controller
{


    /**
     * 获取所有菜单（管理员用）
     */
    public function index(Request $request)
    {
        try {
            $query = Menu::with('children');

            // 搜索
            if ($request->has('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('code', 'like', "%{$search}%")
                      ->orWhere('description', 'like', "%{$search}%");
                });
            }

            // 状态筛选
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            // 类型筛选
            if ($request->has('type')) {
                $query->where('type', $request->type);
            }

            // 分页
            $perPage = $request->get('per_page', 15);
            $menus = $query->orderBy('sort_order')->paginate($perPage);

            return $this->paginate($menus, '获取菜单列表成功');

        } catch (\Exception $e) {
            return $this->error('获取菜单列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 创建菜单
     */
    public function store(Request $request)
    {
        try {
            $data = $this->validateRequest($request, [
                'parent_id' => 'nullable|exists:menus,id',
                'name' => 'required|string|max:100',
                'code' => 'required|string|max:100|unique:menus',
                'icon' => 'nullable|string|max:50',
                'path' => 'nullable|string|max:200',
                'component' => 'nullable|string|max:200',
                'type' => 'required|in:menu,button,page',
                'description' => 'nullable|string|max:500',
                'permissions' => 'nullable|array',
                'permissions.*' => 'string',
                'status' => 'required|in:active,inactive',
                'is_external' => 'boolean',
                'is_visible' => 'boolean',
                'sort_order' => 'integer|min:0',
            ]);

            $menu = Menu::create($data);

            return $this->success($menu, '创建菜单成功', 201);

        } catch (\Exception $e) {
            return $this->error('创建菜单失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取菜单详情
     */
    public function show(Menu $menu)
    {
        try {
            return $this->success($menu->load('children'), '获取菜单详情成功');
        } catch (\Exception $e) {
            return $this->error('获取菜单详情失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新菜单
     */
    public function update(Request $request, Menu $menu)
    {
        try {
            $data = $this->validateRequest($request, [
                'parent_id' => 'nullable|exists:menus,id',
                'name' => 'required|string|max:100',
                'code' => 'required|string|max:100|unique:menus,code,' . $menu->id,
                'icon' => 'nullable|string|max:50',
                'path' => 'nullable|string|max:200',
                'component' => 'nullable|string|max:200',
                'type' => 'required|in:menu,button,page',
                'description' => 'nullable|string|max:500',
                'permissions' => 'nullable|array',
                'permissions.*' => 'string',
                'status' => 'required|in:active,inactive',
                'is_external' => 'boolean',
                'is_visible' => 'boolean',
                'sort_order' => 'integer|min:0',
            ]);

            $menu->update($data);

            return $this->success($menu, '更新菜单成功');

        } catch (\Exception $e) {
            return $this->error('更新菜单失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除菜单
     */
    public function destroy(Menu $menu)
    {
        try {
            // 检查是否有子菜单
            if ($menu->children()->count() > 0) {
                return $this->error('无法删除包含子菜单的菜单', 422);
            }

            $menu->delete();

            return $this->success(null, '删除菜单成功');

        } catch (\Exception $e) {
            return $this->error('删除菜单失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取菜单树结构
     */
    public function tree(Request $request)
    {
        try {
            $user = $request->user();

            if (!$user) {
                return $this->error('用户未登录', 401);
            }

            // 新版本使用平面结构，获取所有活跃可见的菜单
            $menus = Menu::where('status', 'active')
                ->where('is_visible', true)
                ->with(['functions' => function ($query) {
                    $query->where('status', 'active')
                        ->orderBy('sort_order');
                }])
                ->orderBy('sort_order')
                ->get();

            // 过滤用户有权限的菜单
            $filteredMenus = $menus->filter(function ($menu) use ($user) {
                return $menu->userCanAccess($user);
            });

            // 格式化为前端需要的格式
            $formattedMenus = $this->formatMenusForFrontend($filteredMenus);

            return $this->success($formattedMenus, '获取菜单树成功');

        } catch (\Exception $e) {
            return $this->error('获取菜单树失败: ' . $e->getMessage());
        }
    }

    /**
     * 格式化菜单数据为前端需要的格式
     */
    private function formatMenusForFrontend($menus)
    {
        return $menus->map(function ($menu) {
            $formatted = [
                'id' => $menu->id,
                'code' => $menu->code, // 添加code字段，前端需要用作key
                'name' => $menu->name,
                'path' => $menu->path, // 直接使用path字段
                'icon' => $menu->icon,
                'component' => $menu->component,
                'type' => 'menu', // 新版本固定为menu类型
                'is_external' => false, // 新版本不支持外部链接
                'permissions' => [], // 新版本权限通过功能管理
                'sort_order' => $menu->sort_order,
                'functions' => $menu->functions ? $menu->functions->map(function ($function) {
                    return [
                        'id' => $function->id,
                        'code' => $function->code,
                        'name' => $function->name,
                        'level' => $function->level,
                        'sort_order' => $function->sort_order,
                    ];
                }) : []
            ];

            return $formatted;
        });
    }
}
